package com.mangguo.tingjian.config.db;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.mangguo.tingjian.mgtjv3.mapper", sqlSessionFactoryRef = "mgtjvSqlSessionFactory")
public class DataSourceMgtjvConfig {

    @Bean(name = "mgtjvDataSource")
    @ConfigurationProperties("spring.datasource.mgtjv")
    public DataSource mgtjvDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "mgtjvSqlSessionFactory")
    public SqlSessionFactory mgtjvSqlSessionFactory(@Qualifier("mgtjvDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "mgtjvDataSourceTransactionManager")
    public DataSourceTransactionManager mgtjvDataSourceTransactionManager(@Qualifier("mgtjvDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mgtjvSqlSessionTemplate")
    public SqlSessionTemplate mgtjvSqlSessionTemplate(@Qualifier("mgtjvSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
